#!/usr/bin/env node
/**
 * Phase3.5 执行入口脚本
 *
 * 整合Phase3.5验证流程:
 * 1. 实现验证
 * 2. Gap-based评估
 * 3. 生成决策建议
 */

const fs = require('fs');
const path = require('path');
const { verifyImplementation } = require('./phase3.5-implementation-verification');
const { evaluateCustomPanels } = require('./phase4-gap-based-evaluation');

const PROJECT_ROOT = path.resolve(__dirname, '..');

/**
 * 生成Phase3.5 checkpoint
 */
function generateCheckpoint(componentCode, verificationReport, evaluation) {
  const checkpoint = {
    timestamp: new Date().toISOString(),
    phase: 'Phase3.5',
    componentCode,
    status: 'completed',
    verification: {
      filesystemCheck: verificationReport.verification.filesystemCheck.status,
      variantLogicCheck: verificationReport.verification.variantLogicCheck.status,
      auxiliaryAlignment: verificationReport.verification.auxiliaryAlignment.status
    },
    gap: {
      missingPanels: verificationReport.gap.missingPanels.length,
      missingVariantLogic: verificationReport.gap.missingVariantLogic.length,
      auxiliaryMismatches: verificationReport.gap.auxiliaryMismatches.length
    },
    recommendation: verificationReport.recommendation,
    evaluation: {
      needsCustomPanels: evaluation.decision.needsCustomPanels,
      action: evaluation.decision.action,
      missingCount: evaluation.decision.missingCount || 0
    },
    artifacts: {
      verificationReport: `phase3.5/implementation-verification-report.json`,
      evaluationReport: `phase4/gap-based-evaluation.json`,
      panelSpec: evaluation.decision.needsCustomPanels ? `phase4/custom-panel-spec.json` : null
    },
    nextPhase: evaluation.decision.action === 'generate' ? 'Phase4' : 'Phase5'
  };

  // 保存checkpoint
  const checkpointPath = path.join(PROJECT_ROOT, `${componentCode}/checkpoints/P3.5_verification.json`);
  const checkpointDir = path.dirname(checkpointPath);

  if (!fs.existsSync(checkpointDir)) {
    fs.mkdirSync(checkpointDir, { recursive: true });
  }

  fs.writeFileSync(checkpointPath, JSON.stringify(checkpoint, null, 2), 'utf-8');

  return checkpoint;
}

/**
 * 主执行函数
 */
async function runPhase3_5(componentCode) {
  console.log('\n╔════════════════════════════════════════════════════════╗');
  console.log('║         Phase3.5 实现验证阶段 (零信任验证)            ║');
  console.log('╚════════════════════════════════════════════════════════╝\n');
  console.log(`组件: ${componentCode}\n`);

  try {
    // Step 1: 实现验证
    console.log('═══ Step 1/2: 实现验证 ═══\n');
    const verificationReport = await verifyImplementation(componentCode);

    if (verificationReport.verification?.filesystemCheck?.status === 'error') {
      console.error('\n❌ 实现验证失败,无法继续');
      process.exit(1);
    }

    // Step 2: Gap-based评估
    console.log('\n═══ Step 2/2: Gap-based评估 ═══\n');
    const evaluation = await evaluateCustomPanels(componentCode);

    // Step 3: 生成checkpoint
    console.log('\n═══ 生成Checkpoint ===\n');
    const checkpoint = generateCheckpoint(componentCode, verificationReport, evaluation);

    console.log('✅ Phase3.5执行完成');
    console.log(`\n下一阶段: ${checkpoint.nextPhase}`);

    if (checkpoint.nextPhase === 'Phase4') {
      console.log('\n🔧 建议执行:');
      console.log(`   node scripts/phase4-panel-generation.js ${componentCode}`);
    } else {
      console.log('\n✅ 所有面板已实现,可直接进入Phase5');
      console.log(`   npm run phase5 -- ${componentCode}`);
    }

    // 输出汇总
    console.log('\n═══ 验证汇总 ===\n');
    console.log(`文件系统检查: ${checkpoint.verification.filesystemCheck}`);
    console.log(`Variant逻辑:   ${checkpoint.verification.variantLogicCheck}`);
    console.log(`Auxiliary对齐: ${checkpoint.verification.auxiliaryAlignment}`);
    console.log(`\nGap统计:`);
    console.log(`  缺失面板: ${checkpoint.gap.missingPanels}`);
    console.log(`  缺失逻辑: ${checkpoint.gap.missingVariantLogic}`);
    console.log(`  对齐差异: ${checkpoint.gap.auxiliaryMismatches}`);

    // 返回exit code
    const hasErrors = checkpoint.gap.missingPanels > 0;
    process.exit(hasErrors ? 1 : 0);
  } catch (error) {
    console.error('\n❌ Phase3.5执行失败:', error.message);
    console.error(error.stack);
    process.exit(1);
  }
}

// CLI执行
if (require.main === module) {
  const componentCode = process.argv[2];

  if (!componentCode) {
    console.error('用法: node scripts/run-phase3.5.js <ComponentCode>');
    console.error('示例: node scripts/run-phase3.5.js SuccessBlock');
    process.exit(1);
  }

  runPhase3_5(componentCode);
}

module.exports = { runPhase3_5 };
